package org.dromara.oce.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.dto.TypeDto;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.oce.domain.bo.OceMaterialEverydayCensusBo;
import org.dromara.oce.domain.dto.CompilePeopleRecordDataDTO;
import org.dromara.oce.domain.dto.OceMaterialRecordDTO;
import org.dromara.oce.domain.vo.OceMaterialEverydayCensusVo;
import org.dromara.oce.service.OceMaterialEverydayCensusService;
import org.dromara.oce.utils.PlatformParamTransUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 巨量素材每日数据统计
 *
 * @author Lion Li
 * @date 2024-12-24
 * @module 管理平台接口
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oce/materialEverydayCensus")
public class OceMaterialEverydayCensusController extends BaseController {

    private final OceMaterialEverydayCensusService oceMaterialEverydayCensusService;

    /**
     * 查询编辑素材消耗统计列表
     */
    @SaCheckPermission("oce:materialEverydayCensus:listEdit")
    @GetMapping("/listEdit")
    public TableDataInfo<CompilePeopleRecordDataDTO> listEdit(OceMaterialEverydayCensusBo bo, PageQuery pageQuery) {
        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        Long deptId = LoginHelper.getDeptId();
        if (!LoginHelper.isSuperAdmin() && !LoginHelper.isTenantAdmin()) {
            bo.setDeptId(deptId);
        }
        Long deptIdCache = PlatformParamTransUtil.getDynamicDept();
        if (deptIdCache > 0L) {
            bo.setDeptId(deptIdCache);
        }
        return oceMaterialEverydayCensusService.queryEditPageList(bo, pageQuery);
    }

    /**
     * 导出编辑素材消耗列表
     */
    @SaCheckPermission("oce:advertiserEverydayCost:exportEdit")
    @Log(title = "编辑素材消耗", businessType = BusinessType.EXPORT)
    @PostMapping("/exportEdit")
    public void export(OceMaterialEverydayCensusBo bo, HttpServletResponse response) {
        Long deptId = LoginHelper.getDeptId();
        if (!LoginHelper.isSuperAdmin() && !LoginHelper.isTenantAdmin()) {
            bo.setDeptId(deptId);
        }
        Long deptIdCache = PlatformParamTransUtil.getDynamicDept();
        if (deptIdCache > 0L) {
            bo.setDeptId(deptIdCache);
        }
        List<CompilePeopleRecordDataDTO> list = oceMaterialEverydayCensusService.queryEditList(bo);
        ExcelUtil.exportExcel(list, "编辑素材消耗记录", CompilePeopleRecordDataDTO.class, response);
    }

    /**
     * 查询巨量素材每日数据统计列表
     */
    @SaCheckPermission("oce:materialEverydayCensus:list")
    @GetMapping("/list")
    public TableDataInfo<OceMaterialRecordDTO> list(OceMaterialEverydayCensusBo bo, PageQuery pageQuery) {
        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        Long deptId = LoginHelper.getDeptId();
        if (!LoginHelper.isSuperAdmin() && !LoginHelper.isTenantAdmin()) {
            bo.setDeptId(deptId);
        }
        Long deptIdCache = PlatformParamTransUtil.getDynamicDept();
        if (deptIdCache > 0L) {
            bo.setDeptId(deptIdCache);
        }
        TableDataInfo<OceMaterialRecordDTO> tableDataInfo = new TableDataInfo<>();
        List<TypeDto> sum = new ArrayList<>();
        List<OceMaterialRecordDTO> dtos = new ArrayList<>();
        List<OceMaterialEverydayCensusVo> sumList = oceMaterialEverydayCensusService.queryList(bo);
        if (CollectionUtils.isNotEmpty(sumList)) {
            BigDecimal sumNum = sumList.stream().map(OceMaterialEverydayCensusVo::getStatCost).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            TypeDto typeDto = new TypeDto();
            typeDto.setType(sumNum + "");
            typeDto.setDesc("总消耗");
            sum.add(typeDto);
        }
        tableDataInfo.setSum(sum);
        TableDataInfo<OceMaterialEverydayCensusVo> dataInfo = oceMaterialEverydayCensusService.queryPageList(bo, pageQuery);
        List<OceMaterialEverydayCensusVo> list = dataInfo.getRows();
        if (CollectionUtils.isNotEmpty(list)) {
            for (OceMaterialEverydayCensusVo vo : list) {
                OceMaterialRecordDTO dto = new OceMaterialRecordDTO();
                BeanUtil.copyProperties(vo, dto);
                BigDecimal cpmPlatform = dto.getShowCnt() > 0 ? dto.getStatCost().divide(new BigDecimal(dto.getShowCnt()), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(3) : BigDecimal.ZERO;
                BigDecimal ctr = dto.getShowCnt() > 0 ? new BigDecimal(dto.getClickCnt()).divide(new BigDecimal(dto.getShowCnt()), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(2) : BigDecimal.ZERO;
                BigDecimal conversionCost = dto.getConvertCnt() > 0 ? dto.getStatCost().divide(new BigDecimal(dto.getConvertCnt()), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
                dto.setCpmPlatform(cpmPlatform);
                dto.setConversionCost(conversionCost);
                dto.setCtr(ctr);
                dtos.add(dto);
            }
        }
        tableDataInfo.setCode(dataInfo.getCode());
        tableDataInfo.setMsg(dataInfo.getMsg());
        tableDataInfo.setRows(dtos);
        tableDataInfo.setTotal(dataInfo.getTotal());
        return tableDataInfo;
    }

    /**
     * 获取巨量素材每日数据统计详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("oce:materialEverydayCensus:query")
    @GetMapping("/{id}")
    public R<OceMaterialEverydayCensusVo> getInfo(@NotNull(message = "主键不能为空")
                                                  @PathVariable Long id) {
        return R.ok(oceMaterialEverydayCensusService.queryById(id));
    }

    /**
     * 新增巨量素材每日数据统计
     */
    @SaCheckPermission("oce:materialEverydayCensus:add")
    @Log(title = "巨量素材每日数据统计", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody OceMaterialEverydayCensusBo bo) {
        return toAjax(oceMaterialEverydayCensusService.insertByBo(bo));
    }

    /**
     * 修改巨量素材每日数据统计
     */
    @SaCheckPermission("oce:materialEverydayCensus:edit")
    @Log(title = "巨量素材每日数据统计", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody OceMaterialEverydayCensusBo bo) {
        return toAjax(oceMaterialEverydayCensusService.updateByBo(bo));
    }

    /**
     * 删除巨量素材每日数据统计
     *
     * @param ids 主键串
     */
    @SaCheckPermission("oce:materialEverydayCensus:remove")
    @Log(title = "巨量素材每日数据统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(oceMaterialEverydayCensusService.deleteWithValidByIds(List.of(ids), true));
    }
}
